﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using ViewModel = Red.Launcher.ViewModels;

namespace Red.Launcher
{
    public partial class RecentFiles : UserControl
    {
        #region Dependency Properties

        public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register( "Title", typeof( string ), typeof( RecentFiles ) );

        public static readonly DependencyProperty FilterViewProperty =
        DependencyProperty.Register( "FilterView", typeof( ICollectionView ), typeof( RecentFiles ) );

        #endregion Dependency Properties

        #region Public Properties

        public string Title
        {
            get { return (string)GetValue( TitleProperty ); }
            set { SetValue( TitleProperty, value ); }
        }

        public ICollectionView FilterView
        {
            get { return (ICollectionView)GetValue( FilterViewProperty ); }
            private set { SetValue( FilterViewProperty, value ); }
        }

        #endregion Public Properties

        #region C-Tor

        partial void InitializeAnalytics();

        public RecentFiles()
        {
            InitializeComponent();
            
            ViewModel.RecentFiles recentFiles = new ViewModel.RecentFiles();
            FilterView = CollectionViewSource.GetDefaultView( recentFiles.Paths );
            FilterView.Filter = new Predicate<object>( Filter );
            _filter.TextChanged += ( object sender, TextChangedEventArgs e ) => { FilterView.Refresh(); };

            _listbox.MouseDoubleClick += ListBox_MouseDoubleClick;

            DataContext = recentFiles;

            InitializeAnalytics();
        }

        #endregion C-Tor

        #region Event Handlers

        private bool Filter( object obj )
        {
            string filterText = (string)obj;

            if ( string.IsNullOrWhiteSpace( _filter.Text ) || filterText.ToLower().Contains( _filter.Text.ToLower() ) )
            {
                return true;
            }

            return false;
        }

        private void ListBox_MouseDoubleClick( object sender, MouseButtonEventArgs e )
        {
            ListBox box = (ListBox)sender;

            RecentFileActivated?.Invoke( (string)box.SelectedItem );
        }

        #endregion Event Handlers

        #region Events

        public delegate void RecentFileActivatedHandler( string file );
        public event RecentFileActivatedHandler RecentFileActivated;

        #endregion Events
    }
}
